#include "Empacter.h"
#include <iostream>

Empacter::Empacter() :
_id(0)
{
}

void Empacter::SetId(int id)
{
	_id = id;
}

void Empacter::EmpactAudio(IBuffer *data, IBuffer *out, unsigned int &size, InfoAudioBase* info, InfoAudioSpacial* infoSpacial)
{
	InfoBase base;
	void	 *tmpData;
	unsigned int tmpsize = size + sizeof(InfoBase) + sizeof(InfoAudioBase) + (infoSpacial ? sizeof(InfoAudioSpacial) : 0);

	if (out->SizeMax() - out->Size() < tmpsize)
	{
		data->Delete(size);
		size = 0;
		return;
	}
	out->SetEvent(false);
	tmpData = data->Read(size, false);
	base.id = _id;
	base.type = AUDIO;
	base.sizeData = size;
	base.sizeTotalWithoutInfoBase = size + sizeof(InfoAudioBase);
	out->Write(&base, sizeof(InfoBase));
	out->Write(info, sizeof(InfoAudioBase));
	if (infoSpacial)
		out->Write(infoSpacial, sizeof(InfoAudioSpacial));
	out->SetEvent(true);
	out->Write(tmpData, size);
	data->Delete(size);
	size =  tmpsize;
}

unsigned int Empacter::GetPacketSizeWithoutHeader(void *header)
{
	
	try{
	InfoBase* info = reinterpret_cast<InfoBase*>(header);

	return info->sizeTotalWithoutInfoBase;
	
	}
	catch(...)
	{
		return 0;
	}
}

unsigned int Empacter::GetHeaderSize()
{
	return sizeof(InfoBase);
}

void *Empacter::Desempact(void *data, unsigned int &size, Header *header)
{
	if (size < sizeof(InfoBase))
		return NULL;
	try{
	header->base = reinterpret_cast<InfoBase*>(data);

	
	header->spacial = 0;
	if (!header->base || size < header->base->sizeTotalWithoutInfoBase + sizeof(InfoBase))
		return NULL;
	}
	catch(...)
	{
		return NULL;
	}
	size = header->base->sizeTotalWithoutInfoBase + sizeof(InfoBase);
	if (header->base->type == AUDIO)
	{
		header->admin = 0;
		header->audio = (InfoAudioBase*)((char*)data + sizeof(InfoBase));
		if (header->audio->spacial)
		{
			header->spacial = (InfoAudioSpacial*)((char*)data + sizeof(InfoBase) + sizeof(InfoAudioBase));
			return (char*)data + sizeof(InfoBase) + sizeof(InfoAudioBase) + sizeof(InfoAudioSpacial);
		}
		else
		{
			return (char*)data + sizeof(InfoBase) + sizeof(InfoAudioBase);
		}
	}
	else if (header->base->type == ADMIN)
	{
		header->audio = 0;
		header->admin = (InfoAdmin*)((char*)data + sizeof(InfoBase));
		return (char*)data + sizeof(InfoBase) + sizeof(InfoAdmin);
	}
	return (char*)data + sizeof(InfoBase);
}

void Empacter::EmpactAdmin(IBuffer *data, IBuffer *out, unsigned int &size, InfoAdmin* info)
{

}

void Empacter::EmpactText(IBuffer *data, IBuffer *out, unsigned int &size)
{
/*	InfoBase base;
	void	 *tmpData;

	out->SetEvent(false);
	tmpData = data->Read(size);
	base.id = _id;
	base.type = AUDIO;
	base.size = size;
	out->Write(&base, sizeof(InfoBase));
	out->SetEvent(true);
	out->Write(tmpData, size);
	size +=  sizeof(InfoBase);*/
}